//Copyright (c) 2013, Jiang Su Nanyi Digital Dna Science & Technology CO.LTD. All Rights Reserved
/**
 * @首页
 */

/**
 * @页面加载的唯一入口
 * @author huj huj@cpsdna.com 2013-05-14
 */
$(function(){
    //初始化系统
    //初始化页面
    laso.home.init();
});

/**
 * @首页展现
 * @author huj huj@cpsdna.com 2013-05-14
 */
(function(){
	laso.nameSpace('home');
	
	laso.home.userId="" ;
	laso.home.vehicleId="" ;
	
	
	laso.home.date = laso.getDateByDayStepUnderToday(-1); //昨天

	
	laso.home.init = function(){
		parseParams();
		initEvent();
		setTimeout(function(){reComputeWinProperty(); }  ,200);
	};
	
	function  parseParams(){
		var  condEncode= laso.getUrlParamByKey("cond");   // base64密文
		var  condDecode=$.base64.decode(condEncode);
		
		
		laso.home.userId =laso.getUrlParamByKey("USER_ID",condDecode);
		laso.home.vehicleId =laso.getUrlParamByKey("VEHICLE_ID",condDecode);
		laso.home.date  = laso.getUrlParamByKey("DATE",condDecode);
		
		if(laso.isEmpty(laso.home.userId)){
			laso.home.userId ="000578eb041d4c30a56c343c88f5a9eb";
		};
		if(laso.isEmpty(laso.home.vehicleId)){
			laso.home.vehicleId="111";  // 111
		}
		if(laso.isEmpty(laso.home.date)){//laso.getDateByDayStepUnderToday(-1)
			laso.home.date='2016-05-13'; // '2016-04-13'
		}
	}
	
	
	
	function initEvent(){
		// 上翻事假 响应
		$('.page').on('current' , function () {
			var  sectionId= $(this).attr("id");
			if("webDrivingScore"==sectionId){//1 驾驶行为得分
				webDrivingScore();
			}else if("webDrivingDailyMilage"==sectionId){//2-行驶里程
				webDrivingDailyMilage();
			}else if("webDrivingDailyAvgSpeed"==sectionId){//3平均速度
				webDrivingDailyAvgSpeed();
			}else if("webDrivingFuelConsumption"==sectionId){//4平均油耗
				webDrivingFuelConsumption();
			}else if("webDrivingFourEmergency"==sectionId){//5-四急
				webDrivingFourEmergency();
			}else if("webDrivingTime"==sectionId){//6驾驶时间
				webDrivingTime();
			}
			else if("webBracelet"==sectionId){//7手环应用系统
				webDrivingTime();
			}
			else if("webEquipment"==sectionId){//8装备管理系统
				webDrivingTime();
			}
			else if("webContactUs"==sectionId){//9联系我们
				webDrivingTime();
			}else{
				console.log("非定义驾驶行为");
			}
		});
		
		};
	
	function  reComputeWinProperty(){
		var screenH = document.body.offsetHeight;
		$('#appHeight').css("height",screenH*0.6-117+"px"); //28高度  <g class="highcharts-legend" zIndex="7" transform="translate(95,180)" style="/* display: none; */height: 0;"><rect rx="5" ry="5" fill="none" x="0.5" y="0.5" width="185" height="28" stroke="#909090" stroke-width="1" visibility="visible"></rect><g zIndex="1" clip-path="url(#highcharts-4)"><g><g class="highcharts-legend-item" zIndex="1" transform="translate(8,3)"><text x="21" y="15" style="font-family:&quot;Lucida Grande&quot;, &quot;Lucida Sans Unicode&quot;, Verdana, Arial, Helvetica, sans-serif;font-size:12px;cursor:pointer;color:#274b6d;fill:#274b6d;" text-anchor="start" zIndex="2"><tspan x="21">当前行驶时间</tspan></text><rect rx="2" ry="2" fill="#5adaff" x="0" y="4" width="16" height="12" zIndex="3"></rect></g><g class="highcharts-legend-item" zIndex="1" transform="translate(109,3)"><text x="21" y="15" style="font-family:&quot;Lucida Grande&quot;, &quot;Lucida Sans Unicode&quot;, Verdana, Arial, Helvetica, sans-serif;font-size:12px;cursor:pointer;color:#274b6d;fill:#274b6d;" text-anchor="start" zIndex="2"><tspan x="21">上月平均</tspan></text><rect rx="2" ry="2" fill="#efa516" x="0" y="4" width="16" height="12" zIndex="3"></rect></g></g></g></g>
	}
	
	/**
	 *  1 驾驶行为
	 * @returns
	 */
	function  webDrivingScore(){
		var  par={
			     "userId": laso.home.userId , //用户ID
			     "vehicleId": laso.home.vehicleId,//车辆ID
			     "date": laso.home.date//驾驶行为对应日期
		}
		
		laso.ajaxRequest("webDrivingScore",par,function(data){
			if(data.result!=0){
				return ;
			}
			// 绑定 驾驶行为数据
			
			var    vehicleIconUrl= data.detail.vehicleBrand ;
			var    date= data.detail.date ;
			var    score= data.detail.score ;
			var    scoreRate= data.detail.scoreRank ;
			var    realName =  data.detail.realName  ;
			
			//test 
//			vehicleIconUrl ="../static/images/band.png" ;
//			date  =laso.home.date ;
//			score =23 ;
//			scoreRate="89%";
			
			
			$("#webDrivingScore").find("img[name='vehicleIconUrl']").attr("src",vehicleIconUrl);
			$("#webDrivingScore").find("i[name='userName']").text(realName);
			$("#webDrivingScore").find("li[name='date']").text(date);
			$("#webDrivingScore").find("i[name='score']").text(score);
			$("#webDrivingScore").find("span[name='scoreRate']").text(scoreRate);
			
		})
		
	};
	/**
	 * 2 行驶里程
	 */
	function  webDrivingDailyMilage(){
		var  par={
			     "userId": laso.home.userId , //用户ID
			     "vehicleId": laso.home.vehicleId,//车辆ID
			     "date": laso.home.date//驾驶行为对应日期
		}
		
		laso.ajaxRequest("webDrivingDailyMilage",par,function(data){
			if(data.result!=0){
				return ;
			}	
		
			// 绑定 驾驶行为数据
			
			var  milage  = data.detail.milage ;
			var  lastMonthAvgMilage = data.detail.lastMonthAvgMilage ;
			
			//test
//			milage=70 ;
//			lastMonthAvgMilage=180 ;
			
			$("#webDrivingDailyMilage").find("span[name='mile']").text(milage);
			
			$("#webDrivingDailyMilage").find("i[name='currentMile']").find("span").text(milage+"公里");
			$("#webDrivingDailyMilage").find("i[name='avgMile']").find("span").text(lastMonthAvgMilage+"公里");
			
			if(milage>lastMonthAvgMilage){
				$("#webDrivingDailyMilage").find("i[name='currentMile']").find("img").attr("src","../static/images/longIndex.png");
				$("#webDrivingDailyMilage").find("i[name='avgMile']").find("img").attr("src","../static/images/shortIndex.png");
			}else{
				$("#webDrivingDailyMilage").find("i[name='currentMile']").find("img").attr("src","../static/images/shortIndex.png");
				$("#webDrivingDailyMilage").find("i[name='avgMile']").find("img").attr("src","../static/images/longIndex.png");
			}
			
		})
		
	};
	
	/**
	 * 3 平均速度
	 */
	function  webDrivingDailyAvgSpeed(){
		var  par={
			     "userId": laso.home.userId , //用户ID
			     "vehicleId": laso.home.vehicleId,//车辆ID
			     "date": laso.home.date//驾驶行为对应日期
		}
		
		laso.ajaxRequest("webDrivingDailyAvgSpeed",par,function(data){
			if(data.result!=0){
				return ;
			}	
			
			//
			var  speed  = data.detail.speed;
			var  lastMonthAvgSpeed = data.detail.lastMonthAvgSpeed ;
			
			var  speedRatio =(speed+lastMonthAvgSpeed>0)?speed/(speed+lastMonthAvgSpeed):0 ;
			var  lastMonthAvgSpeedRatio =(speed+lastMonthAvgSpeed>0)?lastMonthAvgSpeed/(speed+lastMonthAvgSpeed):0 ;
			
			//test
//			speed=25 ;
//			lastMonthAvgSpeed=87;
			
			$("#webDrivingDailyAvgSpeed").find("i[name='avgSpeed']").find("span").text(speed);
			
			var myCircleSpeed = $.Circles.create({
				  id:                  'avgSpeedPlugin',
				  radius:              60,
				  value:              speedRatio,
				  maxValue:            1,
				  width:               5,
				  text:                speed+"",  //function(value){return value;}
				  colors:              ['#1ca709','#f2a500'],
				  duration:            400,
				  wrpClass:            'circles-wrp',
				  textClass:           'circles-text',
				  valueStrokeClass:    'circles-valueStroke',
				  maxValueStrokeClass: 'circles-maxValueStroke',
				  styleWrapper:        true,
				  styleText:           true
				});
			
			
			var myCircleThisMonthSpeed = $.Circles.create({
				  id:                  'thisMonthSpeedPlugin',
				  radius:              60,
				  value:               lastMonthAvgSpeedRatio,
				  maxValue:            1,
				  width:               10,
				  text:                lastMonthAvgSpeed+"" , //function(value){return value;}
				  colors:              ['#1ca709','#f2a500'],
				  duration:            400,
				  wrpClass:            'circles-wrp',
				  textClass:           'circles-text',
				  valueStrokeClass:    'circles-valueStroke',
				  maxValueStrokeClass: 'circles-maxValueStroke',
				  styleWrapper:        true,
				  styleText:           true
				});
			
			
			
		})
		
	};
	/**
	 * 4 平均油耗
	 */
	function  webDrivingFuelConsumption(){
		var  par={
			     "userId": laso.home.userId , //用户ID
			     "vehicleId": laso.home.vehicleId,//车辆ID
			     "date": laso.home.date//驾驶行为对应日期
		}
		
		laso.ajaxRequest("webDrivingFuelConsumption",par,function(data){
			if(data.result!=0){
			return ;
			}	
			
			var  avgFuel  = data.detail.avgFuel;
			var  lastMonthAvgFuel = data.detail.lastMonthAvgFuel ;
			
			//test
//			avgFuel=80 ;
//			lastMonthAvgFuel=82;
			
			$("#webDrivingFuelConsumption").find("li[name='fuelConsumptionAvg']").find("span").text(avgFuel);
			
			if(avgFuel>lastMonthAvgFuel){
				
				$("#webDrivingFuelConsumption").find("ul[name='fuelConsumptionAvgUl']").find("li:first").text(avgFuel+"L/100Km");
				$("#webDrivingFuelConsumption").find("ul[name='fuelConsumptionAvgUl']").find("li").find("img").attr("src","../static/images/greenLong.png");
				
				$("#webDrivingFuelConsumption").find("ul[name='fuelConsumptionThisMonthAvgUl']").find("li:first").text(lastMonthAvgFuel+"L/100Km");
				$("#webDrivingFuelConsumption").find("ul[name='fuelConsumptionThisMonthAvgUl']").find("li").find("img").attr("src","../static/images/orangeShort.png");
			}else{
				$("#webDrivingFuelConsumption").find("ul[name='fuelConsumptionAvgUl']").find("li:first").text(avgFuel+"L/100Km");
				$("#webDrivingFuelConsumption").find("ul[name='fuelConsumptionAvgUl']").find("li").find("img").attr("src","../static/images/greenShort.png");
				
				$("#webDrivingFuelConsumption").find("ul[name='fuelConsumptionThisMonthAvgUl']").find("li:first").text(lastMonthAvgFuel+"L/100Km");
				$("#webDrivingFuelConsumption").find("ul[name='fuelConsumptionThisMonthAvgUl']").find("li").find("img").attr("src","../static/images/orangeLong.png");
			}
			

		})
		
	};
	/**
	 * 5 四急
	 */
	function  webDrivingFourEmergency(){
		var  par={
			     "userId": laso.home.userId , //用户ID
			     "vehicleId": laso.home.vehicleId,//车辆ID
			     "date": laso.home.date//驾驶行为对应日期
		}
		
		laso.ajaxRequest("webDrivingFourEmergency",par,function(data){
			if(data.result!=0){
			return ;
			}	
			
			var  countRapidAcc = data.detail.countRapidAcc ; // 急加速
			var  countRapidDec = data.detail.countRapidDec ; // 急减速
			var  countSharpTurn = data.detail.countSharpTurn ; //急转弯
			var  countHardBrake = data.detail.countHardBrake ;  //急刹车
			
			
			var  lastMonthAvgCountRapidAcc  = data.detail.lastMonthAvgCountRapidAcc  ; // 急加速
			var  lastMonthAvgCountRapidDec = data.detail.lastMonthAvgCountRapidDec ; // 急减速
			var  lastMonthAvgCountSharpTurn = data.detail.lastMonthAvgCountSharpTurn ; //急转弯
			var  lastMonthAvgCountHardBrake = data.detail.lastMonthAvgCountHardBrake ;  //急刹车
			
			
			
			
			//test 
			countRapidAcc = 121
			countRapidDec = 232; // 急减速
			countSharpTurn = 21 ; //急转弯
			countHardBrake = 5 ;  //急刹车
			
			lastMonthAvgCountRapidAcc  = 2312  ; // 急加速
			lastMonthAvgCountRapidDec = 3123 ; // 急减速
		    lastMonthAvgCountSharpTurn = 511; //急转弯
			lastMonthAvgCountHardBrake = 2111;  //急刹车
			
			
			$("#webDrivingFourEmergency").find("i[name='countSum']").find("span").text(countRapidAcc+countRapidDec+countSharpTurn+countHardBrake);
			
			$("#webDrivingFourEmergency").find("ul[name='rapidAcc']").find("li:first").css("width",toPercent(countRapidAcc/(countRapidAcc+lastMonthAvgCountRapidAcc),0.3));
			$("#webDrivingFourEmergency").find("ul[name='rapidAcc']").find("li:last").css("width",toPercent(lastMonthAvgCountRapidAcc/(countRapidAcc+lastMonthAvgCountRapidAcc),0.3));
			
			$("#webDrivingFourEmergency").find("ul[name='rapidAcc']").find("li:first").find("label").text("当日"+ countRapidAcc +"次" );
			$("#webDrivingFourEmergency").find("ul[name='rapidAcc']").find("li:last").find("label").text("上月"+ lastMonthAvgCountRapidAcc +"次" );
			
			
			$("#webDrivingFourEmergency").find("ul[name='rapidDec']").find("li:first").css("width",toPercent(countRapidDec/(countRapidDec+lastMonthAvgCountRapidDec),0.3));
			$("#webDrivingFourEmergency").find("ul[name='rapidDec']").find("li:last").css("width",toPercent(lastMonthAvgCountRapidDec/(countRapidDec+lastMonthAvgCountRapidDec),0.3));
			
			$("#webDrivingFourEmergency").find("ul[name='rapidDec']").find("li:first").find("label").text("当日"+ countRapidDec +"次" );
			$("#webDrivingFourEmergency").find("ul[name='rapidDec']").find("li:last").find("label").text("上月"+ lastMonthAvgCountRapidDec +"次" );
			
			$("#webDrivingFourEmergency").find("ul[name='sharpTurn']").find("li:first").css("width",toPercent(countSharpTurn/(countSharpTurn+lastMonthAvgCountSharpTurn),0.3));
			$("#webDrivingFourEmergency").find("ul[name='sharpTurn']").find("li:last").css("width",toPercent(lastMonthAvgCountSharpTurn/(countSharpTurn+lastMonthAvgCountSharpTurn),0.3));
			
			$("#webDrivingFourEmergency").find("ul[name='sharpTurn']").find("li:first").find("label").text("当日"+ countSharpTurn +"次" );
			$("#webDrivingFourEmergency").find("ul[name='sharpTurn']").find("li:last").find("label").text("上月"+ lastMonthAvgCountSharpTurn +"次" );
			
			$("#webDrivingFourEmergency").find("ul[name='hardBrake']").find("li:first").css("width",toPercent(countHardBrake/(countHardBrake+lastMonthAvgCountHardBrake),0.3));
			$("#webDrivingFourEmergency").find("ul[name='hardBrake']").find("li:last").css("width",toPercent(lastMonthAvgCountHardBrake/(countHardBrake+lastMonthAvgCountHardBrake),0.3));
			
			$("#webDrivingFourEmergency").find("ul[name='hardBrake']").find("li:first").find("label").text("当日"+ countHardBrake +"次" );
			$("#webDrivingFourEmergency").find("ul[name='hardBrake']").find("li:last").find("label").text("上月"+ lastMonthAvgCountHardBrake +"次" );
			
			
		})
		
	};
	/**
	 * 6 驾驶时间
	 */
	function  webDrivingTime(){
		var  par={
			     "userId": laso.home.userId , //用户ID
			     "vehicleId": laso.home.vehicleId,//车辆ID
			     "date": laso.home.date//驾驶行为对应日期
		}
		
		laso.ajaxRequest("webDrivingTime",par,function(data){
			if(data.result!=0){
				return ;
			}	
			var  DriveTime = data.detail.DriveTime ; //   当日行驶时间
			var  lastMonthAvgDriveTime = data.detail.lastMonthAvgDriveTime ; // 上个月单日平均时间
			var  totalDriveTime = data.detail.totalDriveTime ; // 上个月总行驶时间
			
			
			//test 
//			data.detail.DriveTime=23 ;
//			data.detail.lastMonthAvgDriveTime =89 ;
//			data.detail.totalDriveTime=200;
			
			$("#webDrivingTime").find("i[name='driveTime']").find("span").text(DriveTime);   // totalDriveTime=>    DriveTime
			
			var  chartsData = getDrivingTimeColumnChartData(data);
			 
			 $("#webDrivingTime").find("ul[name='histogramCon']").find("div").highcharts(chartsData) ;
			 
		})
		
	};
	
	
	
	
	/**
	 * @组织按时间柱状图数据
	 * @return {jsonData}
	 * @author wangb wangb@cpsdna.com 2013-04-22
	 */
	function getDrivingTimeColumnChartData(data){
		var chartxAxis = [''];
		var driveTimeData = [];
		var lastMonthAvgDriveTimeData = [];
		var step = 1;
		driveTimeData.push(data.detail.DriveTime) ;
		lastMonthAvgDriveTimeData.push(data.detail.lastMonthAvgDriveTime)
		
		var chartData = {
            chart: {
                type: 'column',
                backgroundColor:''  //背景颜色
            },
            colors:['#5adaff','#efa516'],
            title: {
                text: ''      //主标题
            },
            subtitle: {
                text: ''  //副标题
            },
            xAxis: {
                categories: chartxAxis,
                endOnTick:true,
	            labels: {
                    rotation: 90,
                    align: 'right',
                    step:step,
                    style: {
                    	color: '#efa516',   //x轴文字颜色
                        fontSize: '13px',
                        fontFamily: 'Verdana, sans-serif'
                    }
                },
                lineColor:"#0063CF"  ,  // x轴线条颜色
                lineWidth:'3'
            },
            yAxis: {
                min: 0,
                title: {
                    text: '' //y轴标识
                },
                gridLineColor:''   //与X轴平行的线条颜色
            },
            tooltip: {
                backgroundColor: '#FCFFC5',   // 背景颜色
                borderColor: '',         // 边框颜色
                borderRadius: 4,             // 边框圆角
                borderWidth: 1,               // 边框宽度
                shadow: true,                 // 是否显示阴影
                animation: true,             // 是否启用动画效果
                style: {                      // 文字内容相关样式
                    color: "#000",
                    fontSize: "12px",
                    fontWeight: "blod",
                    fontFamily: "Courir new"
                },
            	
                headerFormat: '<ul>',
                pointFormat: '<li ><span style="color:{series.color};">{series.name}: </span>' +
                    '<span><b>{point.y:1f} 分钟</b></span></li>',
                footerFormat: '</ul>',
                shared: true,
                useHTML: true,
                
                enabled: true //,
//                formatter: function() {
//                    return this.series.name+': '+ this.y +'分钟' ;
//                }
                
            },
                
            plotOptions: {
                column: {
                    pointPadding: 0.2,
                    borderWidth: 0 ,
                    pointWidth:30,
                    dataLabels:{ 
                    	enabled:true ,
                    	color:"#efa516" ,
                    	formatter:function(){
//                    		 if(this.y<=1)
//                    		     return ""
//                    		else 
                    		    return  this.y+'分钟'
                    		}
                    
                    }  //显示标注值
                }
            },
            credits: {
                enabled: false
            },
            series: [{
                name: '当前行驶时间',
                data: [driveTimeData],
                showInLegend: false  //横坐标  标签值不显示
            }, {
                name: '上月平均时间',
                data: lastMonthAvgDriveTimeData,
                showInLegend: false  //横坐标  标签值不显示
            }]
        };
		return chartData;
	};
	
	function toPercent(number,min){
		min =0.10;
		var  num = parseFloat(number,10);
		if(!laso.isEmpty(min)&&(num<=min&&num>0)){
			//return  min+'%';
			return  (Math.round(min * 10000)/100).toFixed(2) + '%';
		}
		return   (Math.round(num * 10000)/100).toFixed(2) + '%';
	}
	

})();